#include "serialwidget.h"
#include "ui_serialwidget.h"
#include <QSerialPortInfo>
#include<QDebug>

#include"serialplot.h"
serialWidget::serialWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::serialWidget)
{
    ui->setupUi(this);

    connect(ui->pushButton,&QPushButton::clicked,this,&serialWidget::serialplotBtnOpenClose);  //打开关闭串口
}

serialWidget::~serialWidget()
{
    delete ui;
}

//将扫描到的串口名称，更新到界面中
void serialWidget::scanCOM_Slots(QStringList serialPortName){
    ui->comboBox->clear();
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts()){
        ui->comboBox->addItem(info.portName());
    }
}
//打开关闭串口
void serialWidget::serialplotBtnOpenClose(){

    if(ui->pushButton->text() == "打开串口"){
        SerialPlot::COMINFO info;
        QString Cname = ui->comboBox->currentText();
        int Cbaud = ui->comboBox_2->currentText().toInt();
        float CstopBits = ui->comboBox_3->currentText().toFloat();
        int CdataBits = ui->comboBox_4->currentText().toInt();
        QString Cparity = ui->comboBox_5->currentText();

        QSerialPort::BaudRate baudRate = QSerialPort::BaudRate::Baud115200;
        QSerialPort::DataBits dataBits = QSerialPort::DataBits::Data8;
        QSerialPort::Parity   parity = parity = QSerialPort::Parity::NoParity;
        QSerialPort::StopBits stopBits = stopBits = QSerialPort::StopBits::OneStop;

        if( Cbaud == 115200)
            baudRate = QSerialPort::BaudRate::Baud115200;
        else if( Cbaud == 9600)
            baudRate = QSerialPort::BaudRate::Baud9600;
        else
            baudRate = QSerialPort::BaudRate::Baud115200;;


        if(CdataBits == 8)
            dataBits = QSerialPort::DataBits::Data8;
        else if(CdataBits == 7)
            dataBits = QSerialPort::DataBits::Data7;
        else if(CdataBits == 6)
            dataBits = QSerialPort::DataBits::Data6;
        else
            dataBits = QSerialPort::DataBits::Data5;


        if(Cparity == "无")
            parity = QSerialPort::Parity::NoParity;
        else if( Cparity == "奇校验" )
            parity = QSerialPort::Parity::OddParity;
        else
            parity = QSerialPort::Parity::EvenParity;

        if(CstopBits == 1)
            stopBits = QSerialPort::StopBits::OneStop;
        else if(CstopBits == 1.5)
            stopBits = QSerialPort::StopBits::OneAndHalfStop;
        else
            stopBits = QSerialPort::StopBits::TwoStop;


        info.name = Cname;
        info.baud = baudRate;
        info.dataBits = dataBits;
        info.parity = parity;
        info.stopBits = stopBits;
        emit openSerial_Signal(info);
    }
    else{
        emit closeSerial_Signal();
    }
}

//串口已打开/已关闭
void serialWidget::serialIsConnect_Slots(bool isCon){
    if( isCon )
        ui->pushButton->setText("关闭串口");
    else
        ui->pushButton->setText("打开串口");
}
